package com.jicheng.config.exception;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.jicheng.ext.exceptions.BaseException;
import com.jicheng.ext.response.ErrResponse;
import com.jicheng.framework.utils.JsonUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.NotAllowedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.NotSupportedException;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author bright
 * @Description: 全局异常处理类
 * @date 2019/5/9 10:03
 */
@ControllerAdvice//组合注解，里面含有Component
public class BaseExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(Exception.class)
    public void defultExcepitonHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        ErrResponse responseResult = null;
        if (e instanceof BaseException) {
            //自定义异常
            BaseException baseException = (BaseException) e;
            responseResult = new ErrResponse(baseException.getCode(), baseException.getMsg());
            // 打印堆栈信息
            logger.warn(e.getMessage() + "," + JsonUtils.toJson(e));
//            return responseResult;
        } else if (e instanceof NotFoundException) {
            e.printStackTrace();
            responseResult = new ErrResponse(404, "找不到路径");
        } else if (e instanceof NotAllowedException) {
            e.printStackTrace();
            responseResult = new ErrResponse(403, "禁止访问");
        } else if (e instanceof JsonProcessingException) {
            e.printStackTrace();
            responseResult = new ErrResponse(499, "错误JSON");
        } else if (e instanceof NotSupportedException) {
            e.printStackTrace();
            responseResult = new ErrResponse(415, "不支持的媒体类型");
        }else if(e instanceof UnauthorizedException){
//            e.printStackTrace();
            responseResult = new ErrResponse(515, "权限不够！");
        }else if(e instanceof org.apache.shiro.authc.AuthenticationException){
//            e.printStackTrace();
            responseResult = new ErrResponse(615, "token认证失败！请重新登录！");
        } else {
            //TODO 对登陆的信息校验

//            responseResult = new ErrResponse(500, "服务器繁忙" + JsonUtils.toJson(e));
            // 打印堆栈信息
//            String error = JsonUtils.toJson(e).replaceAll("\\\"","");
//            logger.error("error_{}_stack_{}" , e.getMessage() , error);
            e.printStackTrace();
        }
        JSONObject result = new JSONObject();
        result.put("errCode", responseResult.getErrCode());
        result.put("errMsg", responseResult.getErrMsg());
        //写json数据到客户端
        this.writeJson(response, result);
    }

    private void writeJson(HttpServletResponse response, JSONObject json) {
        PrintWriter out = null;
        try {
            //设定类容为json的格式
            response.setContentType("application/json;charset=UTF-8");
            out = response.getWriter();
            //写到客户端
            out.write(json.toJSONString());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
